#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安装脚本
用于安装样本管理系统的依赖包
"""

import sys
import subprocess
import os
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("错误: 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        return False
    print(f"Python版本检查通过: {sys.version}")
    return True

def install_package(package):
    """安装单个包"""
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        return True
    except subprocess.CalledProcessError:
        return False

def install_requirements():
    """安装requirements.txt中的依赖"""
    requirements = [
        "PyQt6==6.6.1",
        "pyserial==3.5",
        "openpyxl==3.1.2",
        "Pillow==10.1.0",
        "cryptography==41.0.7",
        "python-dateutil==2.8.2"
    ]
    
    print("开始安装依赖包...")
    
    for package in requirements:
        print(f"正在安装 {package}...")
        if install_package(package):
            print(f"✓ {package} 安装成功")
        else:
            print(f"✗ {package} 安装失败")
            return False
    
    return True

def create_directories():
    """创建必要的目录"""
    directories = [
        "backups",
        "images",
        "logs",
        "exports",
        "templates"
    ]
    
    print("创建必要的目录...")
    
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
        print(f"✓ 创建目录: {directory}")

def create_config_file():
    """创建默认配置文件"""
    config_content = '''{
  "database": {
    "path": "sample_management.db",
    "backup_interval": 24,
    "backup_path": "backups/"
  },
  "communication": {
    "tcp": {
      "default_host": "192.168.137.199",
      "default_port": 5000,
      "timeout": 30,
      "heartbeat_interval": 30
    },
    "serial": {
      "default_port": "COM1",
      "default_baudrate": 9600,
      "data_bits": 8,
      "stop_bits": 1,
      "parity": "N"
    }
  },
  "ui": {
    "window_size": [1400, 900],
    "window_position": [100, 100],
    "theme": "default",
    "language": "zh_CN"
  },
  "export": {
    "default_format": "excel",
    "excel_template": "templates/excel_template.xlsx",
    "pdf_template": "templates/pdf_template.pdf"
  },
  "hospital": {
    "name": "",
    "address": "",
    "contact": "",
    "logo_path": ""
  },

  "warning_ranges": {
    "HbA1c": {"min": 4.0, "max": 6.0, "unit": "%"},
    "Glucose": {"min": 3.9, "max": 6.1, "unit": "mmol/L"},
    "Cholesterol": {"min": 3.1, "max": 5.7, "unit": "mmol/L"}
  },
  "logging": {
    "level": "INFO",
    "file": "sample_management.log",
    "max_size": 10,
    "backup_count": 5
  }
}'''
    
    try:
        with open("config.json", "w", encoding="utf-8") as f:
            f.write(config_content)
        print("✓ 创建配置文件: config.json")
        return True
    except Exception as e:
        print(f"✗ 创建配置文件失败: {e}")
        return False

def test_imports():
    """测试导入"""
    print("测试模块导入...")
    
    try:
        import PyQt6
        print("✓ PyQt6 导入成功")
    except ImportError:
        print("✗ PyQt6 导入失败")
        return False
    
    try:
        import serial
        print("✓ pyserial 导入成功")
    except ImportError:
        print("✗ pyserial 导入失败")
        return False
    
    try:
        import openpyxl
        print("✓ openpyxl 导入成功")
    except ImportError:
        print("✗ openpyxl 导入失败")
        return False
    
    try:
        from PIL import Image
        print("✓ Pillow 导入成功")
    except ImportError:
        print("✗ Pillow 导入失败")
        return False
    
    return True

def main():
    """主函数"""
    print("=" * 50)
    print("样本管理系统安装程序")
    print("=" * 50)
    
    # 检查Python版本
    if not check_python_version():
        return False
    
    # 安装依赖
    if not install_requirements():
        print("依赖安装失败，请检查网络连接或手动安装")
        return False
    
    # 创建目录
    create_directories()
    
    # 创建配置文件
    if not create_config_file():
        print("配置文件创建失败")
        return False
    
    # 测试导入
    if not test_imports():
        print("模块导入测试失败")
        return False
    
    print("\n" + "=" * 50)
    print("安装完成！")
    print("=" * 50)
    print("现在可以运行以下命令启动系统:")
    print("python run.py")
    print("或")
    print("python sample_management_system.py")
    print("\n首次运行时会提示创建管理员账号")
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1) 